//
//  UIApplication.swift
//  
//
//  Created by tangbl93 on 2021/1/5.
//

import UIKit

// MARK: App's Data
public extension UIApplication {
    
    /// The app's name
    static var yx_appName: String {
        guard let yx_appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String else {
            return yx_bundleName
        }
        return yx_appName
    }
    
    /// The app's version
    static var yx_appVersion: String {
        return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0"
    }
    
    /// The app's build number
    static var yx_appBuild: String {
        return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String ?? "1"
    }
    
    /// The app's bundle identifier
    static var yx_bundleIdentifier: String {
        return Bundle.main.object(forInfoDictionaryKey: kCFBundleIdentifierKey as String) as? String ?? ""
    }
    
    /// The app's bundle name
    static var yx_bundleName: String {
        return Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) as? String ?? ""
    }
}

// MARK: Window's Properties
public extension UIApplication {
    
    /// window safeArea insets
    static var yx_safeAreaInsets: UIEdgeInsets {
        if #available(iOS 11.0, *) {
            return UIApplication.shared.keyWindow?.safeAreaInsets ?? UIEdgeInsets.zero
        }
        return UIEdgeInsets.zero
    }

    // window statusBar frame
    static var yx_statusBarFrame: CGRect {
        var statusBarFrame = UIApplication.shared.statusBarFrame
        #if swift(>=5.1)
        if #available(iOS 13, *) {
            if let statusBarManager = UIApplication.shared.keyWindow?.windowScene?.statusBarManager {
                statusBarFrame = statusBarManager.statusBarFrame
            }
        }
        #endif
        return statusBarFrame
    }
}

/// Utilities
public extension UIApplication {
    
    /// remove SplashBoard Directory
    static func yx_removeSplashBoardDirectory() {
        let filePath = NSHomeDirectory() + "/Library/SplashBoard"
        if FileManager.default.fileExists(atPath: filePath) {
            try? FileManager.default.removeItem(atPath: filePath)
        }
    }
    
    /// openURL
    static func yx_open(_ url: String,
                        options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:],
                        completionHandler completion: ((Bool) -> Void)? = nil) {
        
        guard let urlData = URL(string: url) else { return }
        UIApplication.shared.open(urlData, options: options, completionHandler: completion)
    }
}
